import Vue from 'vue'
import { TASK_CODE } from '@/store/mutation-types'
import { Login } from '@/api/index'

const user = {
  state: {
    username: '',
    permissionList: []
  },

  mutations: {
    SET_REALNAME: (state, realname) => {
      state.realname = realname
    },
    SET_PERMISSION_LIST: (state, permissionList) => {
      state.permissionList = []
      state.permissionList = permissionList
    }
  },
  actions: {
    // 获取用户信息
    GetPermissionList ({ commit }) {
      return new Promise((resolve, reject) => {
        Login.getSystemMenu({ taskCode: Vue.ls.get(TASK_CODE) }).then(response => {
          const result = response[Vue.prototype.$response.DATA]
          const menuData = result.menuList
          const realname = result.realname
          commit('SET_REALNAME', realname)

          if (menuData && menuData.length > 0) {
            menuData.forEach((item, index) => {
              if (item.children) {
                const hasChildrenMenu = item.children.filter((i) => {
                  return !i.hidden || i.hidden === false
                })
                if (hasChildrenMenu === null || hasChildrenMenu.length === 0) {
                  item.hidden = true
                }
              }
            })
            commit('SET_PERMISSION_LIST', JSON.parse(JSON.stringify(menuData)))
          } else {
            const msg = 'getPermissionList: permissions must be a non-null array !'
            reject(msg)
          }
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        Vue.ls.clear()
        commit('SET_PERMISSION_LIST', [])
        resolve()
      })
    }
  }
}

export default user
